extends Control

@export var player:int
@onready var v_box_container: VBoxContainer = $VBoxContainer
const PLAYER_SAVE_GEM = preload("res://scenes/player/player_save_gem.tscn")
const CARD = preload("res://scenes/card/card.tscn")
# Called when the node enters the scene tree for the first time.
func _ready() -> void:
	GameManager.save_coin.connect(set_save_coin)
	GameManager.update_coin_signal.connect(update_info)
	pass # Replace with function body.


# Called every frame. 'delta' is the elapsed time since the previous frame.
func _process(delta: float) -> void:
	pass
	
@onready var h_box_container_2: HBoxContainer = $HBoxContainer2
@onready var card: Node2D = $HBoxContainer3/Card
@onready var card_2: Node2D = $HBoxContainer3/Card2
@onready var card_3: Node2D = $HBoxContainer3/Card3
@onready var h_box_container_3: HBoxContainer = $HBoxContainer3
@onready var h_box_container: HBoxContainer = $HBoxContainer
@onready var score: Label = $score

func update_info():
	score.text = str(GameManager.players[player].prestige_points)
	for item in h_box_container_2.get_children().size():
		var node = h_box_container_2.get_children()[item].get_node('Label')
		node.text = str(GameManager.players[player].gems[item])
	var cards = [ card ,card_2,card_3]
	var pos = 0
	for item in GameManager.players[player].reserved_cards:
		var flag = false
		for card in h_box_container_3.get_children():
			if card.card_info == item:
				pos += 48
				flag = true
		if !flag:
			var card_instance = CARD.instantiate()
			card_instance.initialize(item,-1)
			card_instance.is_save_card = true
			card_instance.scale = Vector2(0.2,0.2)
			card_instance.position.y += 24 
			h_box_container_3.add_child(card_instance)
			card_instance.position.x += pos
	var node = h_box_container.get_children()
	for idx in range(5):
		node[idx].get_node('Label').text = str(GameManager.players[player].bonuses[idx])

func set_save_coin():
	if player == 0:
		for index in range(6):
			if GameManager.players[0].save_coin[index] != 0:
				var flag = false
				for item in v_box_container.get_children():
					if item.color == index:
						flag = true
						item.update_info()
				if not flag:
					var instance =  PLAYER_SAVE_GEM.instantiate()
					instance.color = index
					instance.initNode()
					instance.update_info()
					v_box_container.add_child(instance)
				
				
func _on_h_box_container_3_gui_input(event: InputEvent) -> void:
	if event is InputEventMouseButton:
		if event.button_index == MOUSE_BUTTON_LEFT and event.pressed:
			GameManager.show_save_card_signal.emit()
